package com.wesh.uaa.config.providers;

import com.wesh.uaa.service.WeshUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@Component
public class UsernamePasswordAuthenticationProvider implements AuthenticationProvider {

    /**
     * 这里使用 UserDetailService 进行加载用户信息
     */
    @Autowired
    WeshUserDetailService userDetailService;

    /**
     * 认证方法
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String principle = authentication.getPrincipal().toString(); //username
        String credential = authentication.getCredentials().toString(); //password
        UserDetails userDetails = userDetailService.loadUserByUsername(principle);
        return new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(),userDetails.getAuthorities());
    }

    /**
     * 判断是不是使用此 provider 进行认证操作，返回true 则在认证的时候执行上面的 authenticate() 方法
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(UsernamePasswordAuthenticationToken.class);
    }
}
